<?php

	namespace App\Http\Controllers\Admin;

	use Dompdf\Dompdf;
	use Illuminate\Http\Request;
	use App\Http\Controllers\Controller;
	use DB;

	class ExcelPosController extends Controller
	{

		//字段在Excel中的位置
		public function excelPos(Request $request)
		{
			$id = $request->id; //a_std_tool_rel 的 id
			if ($request->isMethod('POST')) {
				$post_data = $request->except([
					'id',
					'_token',
					'file',
					'std_id',
					'tool_name',
					'add',
					'pos_id',
                    "_form_token"
				]);
				// $val = strtoupper($val); //转成大写字母
				foreach ($post_data as $k => $val) {
					$post_data[$k] = strtoupper($val); //转成大写字母
				}
				//            dd($post_data);
				// $post_data['line_num'] = intval($post_data['line_num']); //转成整数
				DB::beginTransaction();
				try {
					if (isset($request->add)) {   //添加
						$post_data['std_tool_rel_id'] = $id;
						$result = DB::table('a_excel_pos')->insertGetId($post_data);
						$pos_id = $result;
					}
					else {   //修改
						//update 返回受影响的行数
						$result = DB::table('a_excel_pos')->where([
							'std_tool_rel_id' => $id,
							'id'              => $request->pos_id
						])->update($post_data);
						$pos_id = $request->pos_id;
					}
					if ($result && $request->is_default == 1) {
						DB::table('a_excel_pos')->where('std_tool_rel_id', $id)->where('id', '!=', $pos_id)->update(['is_default' => 0]);
					}
					DB::commit();
				} catch (\Exception $e) {
					DB::rollBack();
					return '操作失败！' . $e->getMessage();
				}
				/*  //编写验证规则
				$arr = [
					'file' => 'file|mimetypes:application/vnd.ms-excel',//有的xls文件验证不通过，暂注释掉
				];
				//进行验证
				$request->validate($arr); */
				//如果验证通过，继续向下执行...
				if ($request->hasFile('file') && $request->file->isValid()) {
					$o_name = $request->name === '默认' ? '' : $request->name;
					$path = $request->file->storeAs("ExcelTemplate/{$request->std_id}", $request->tool_name . $o_name . '.xls', 'public');
				}
				return 1;
			}
			else {
				$sql = "SELECT
                        A.id,
                        A.std_id,
                        A.tool_id,
                        B.num,
                        C.`name`
                    FROM
                        a_std_tool_rel A
                    LEFT JOIN a_standard B ON A.std_id = B.id
                    LEFT JOIN a_tool C ON A.tool_id = C.id
                    WHERE
                        A.id = :id";
				$info_data = DB::select($sql, ['id' => $id]);
				$info_data = $info_data[0]; //绑定的标准

				//模板
				if (isset($request->pos_id)) {
					$data = DB::table('a_excel_pos')->where('std_tool_rel_id', $id)->where('id', $request->pos_id)->first();
				}
				else {
					$data = DB::table('a_excel_pos')->where('std_tool_rel_id', $id)->where('is_default', 1)->first();
				}
				if (!$data) {
					# 如果记录不存在，就插入一条
					$res = DB::table('a_excel_pos')->insert([
						'std_tool_rel_id' => $id,
						'is_default'      => 1
					]);
					$data = DB::table('a_excel_pos')->where('std_tool_rel_id', $id)->first();
				}
				//判断模板文件是否存在
				$o_name = $data->name === '默认' ? '' : $data->name;
				$template_file = "./storage/ExcelTemplate/{$info_data->std_id}/{$info_data->name}{$o_name}.xls"; //考虑到兼容Linux，斜杠用“/”
				$exist_template = file_exists($template_file);
				if ($request->expectsJson()) {
					$rtdata = [
						'data'           => $data,
						'exist_template' => $exist_template,
						'template_file'  => $template_file
					];
					return $rtdata;
				}
				$data_tmp = DB::table('a_excel_pos')->where('std_tool_rel_id', $id)->get();
				$o_std_rels = DB::table('a_std_tool_rel as a')->leftJoin('a_standard as b', 'a.std_id', '=', 'b.id')->where('a.tool_id', $info_data->tool_id)->where('a.std_id', '!=', $info_data->std_id)->select('a.id', 'b.num')->get();  //绑定的其他检测标准，用于同步位置
				return view('admin.excelPos.excelPos', compact('info_data', 'data', 'exist_template', 'data_tmp', 'template_file', 'o_std_rels'));
			}
		}

		//下载模板
		public function downLoadTemplate(Request $request)
		{
			$template_file = "/storage/ExcelTemplate/{$request->std_id}/{$request->name}.xls?id=" . time(); //考虑到兼容Linux，斜杠用“/”
			if (isAdmin()) {
				dd($template_file);
			}
			return redirect($template_file);
		}

		//下载封面 封底模板
		public function downLoadTemplateFMFD(Request $request)
		{
			$template_file = "/storage/ExcelTemplate/{$request->FMFD}.xls"; //考虑到兼容Linux，斜杠用“/”
			return redirect($template_file);
		}

		public function excelPosAjax()
		{
			$stdid = request()->std_id;
			$toolid = request()->tool_id;
			if (!$stdid || !$toolid) {
				return 0;
			}
			$std_tool_rel_id = DB::table('a_std_tool_rel')->where([
				'std_id'  => $stdid,
				'tool_id' => $toolid
			])->value('id');
			$data_tmp = DB::table('a_excel_pos')->where('std_tool_rel_id', $std_tool_rel_id)->select('id', 'name')->get();
			return $data_tmp;
		}

		public function excelPosDetailAjax()
		{
			$excel_pos_id = request()->excel_pos_id;
			if (!$excel_pos_id) {
				return out(0, '参数错误');
			}
			$info = DB::table('a_excel_pos_detail')->where(['excel_pos_id' => $excel_pos_id])->value('info');
			$info = json_decode($info, true);
			$std_tool_item_rel_id = request()->std_tool_item_rel_id;
			$condition_key_id = request()->condition_key_id;
			if (request()->isMethod('post')) {
				$rInfo = request()->info;
				$inInfo = [];
				foreach ($rInfo as $k => $value) {
					$value['pos_end'] = ABC2decimal($value['pos_start']) > ABC2decimal($value['pos_end']) ? $value['pos_start'] : $value['pos_end'];

					$inInfo[$value['id']]['pos_start'] = strtoupper($value['pos_start']);
					$inInfo[$value['id']]['pos_end'] = strtoupper($value['pos_end']);
					//$inInfo[$value['id']]['line_num'] = $value['line_num'];
				}
				//修改试验数据 || 修改试验条件 || 修改检测项目
				if ($std_tool_item_rel_id) {
					$info[$std_tool_item_rel_id]['testdata_key'] = $inInfo;
				}
				else if ($condition_key_id) {
					$info[$condition_key_id]['condition_key'] = $inInfo;
				}
				else {
					$info = $inInfo;
				}
				$res = DB::table('a_excel_pos_detail')->where(['excel_pos_id' => $excel_pos_id])->update(['info' => json_encode($info)]);
				return $res;
			}
			else {
				if (!$info) {
					if ($std_tool_item_rel_id || $condition_key_id) {   //必须先指定项目模板
						return out(0, '必须先指定项目模板');
					}
					$info = request()->info;

					$inInfo = [];
					foreach ($info as $k => $value) {
						$value['pos_end'] = ABC2decimal($value['pos_start']) > ABC2decimal($value['pos_end']) ? $value['pos_start'] : $value['pos_end'];

						$inInfo[$value['id']] = [
							"pos_start" => strtoupper($value['pos_start']),
							"pos_end"   => strtoupper($value['pos_end']),
							//"line_num"  => $value['line_num'],
						];
					}
					$res = DB::table('a_excel_pos_detail')->insert([
						'excel_pos_id' => $excel_pos_id,
						'info'         => json_encode($inInfo)
					]);
					if ($res) {
						return out(1, '指定模板成功！');
					}
				}
				else {
					//添加试验数据
					if ($std_tool_item_rel_id) {
						if (!isset($info[$std_tool_item_rel_id]['testdata_key'])) {
							$testdata_key_info = request()->info;
							$inInfo = [];
							foreach ($testdata_key_info as $k => $value) {
								$value['pos_end'] = ABC2decimal($value['pos_start']) > ABC2decimal($value['pos_end']) ? $value['pos_start'] : $value['pos_end'];

								$inInfo[$value['id']] = [
									"pos_start" => strtoupper($value['pos_start']),
									"pos_end"   => strtoupper($value['pos_end']),
									//"line_num"  => $value['line_num'],
								];
							}
							$info[$std_tool_item_rel_id]['testdata_key'] = $inInfo;
							$res = DB::table('a_excel_pos_detail')->where(['excel_pos_id' => $excel_pos_id])->update(['info' => json_encode($info)]);
							if ($res) {
								return out(1, '指定模板成功！');
							}
						}
						$info = $info[$std_tool_item_rel_id]['testdata_key'];
					}
					//添加试验条件
					if ($condition_key_id) {
						if (!isset($info[$condition_key_id]['condition_key'])) {
							$condition_key_info = request()->info;
							$inInfo = [];
							foreach ($condition_key_info as $k => $value) {
								$value['pos_end'] = ABC2decimal($value['pos_start']) > ABC2decimal($value['pos_end']) ? $value['pos_start'] : $value['pos_end'];

								$inInfo[$value['id']] = [
									"pos_start" => strtoupper($value['pos_start']),
									"pos_end"   => strtoupper($value['pos_end']),
									//"line_num"  => $value['line_num'],
								];
							}
							$info[$condition_key_id]['condition_key'] = $inInfo;
							$res = DB::table('a_excel_pos_detail')->where(['excel_pos_id' => $excel_pos_id])->update(['info' => json_encode($info)]);
							if ($res) {
								return out(1, '指定模板成功！');
							}
						}
						$info = $info[$condition_key_id]['condition_key'];
					}
				}
			}
			return $info;
		}

		//同步位置
		public function syncPos()
		{
			$fromId = request('from_id', '');
			$toId = request('to_id', '');
			$fromData = DB::table('a_excel_pos')
				->where('std_tool_rel_id',$fromId)
				->select('company','line_num','report_num','come_date','test_date','sample_count','temp','hum','pressure','wea','serial_num1','serial_num2','sample_num1','sample_num2','self_num1','self_num2','voltage1','voltage2','class1','class2','res1','res2','valid_date1','valid_date2','sample_rowspann')
				->first();
			$fromData = (array)$fromData;
			$res = DB::table('a_excel_pos')->where('std_tool_rel_id',$toId)->update($fromData);
			return $res ? 1 : 0;
		}
	}
